package com.wang.vedio.player;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.PayDialog;
import com.vondear.rxui.view.dialog.RxDialogDownload;
import com.wang.vedio.R;
import com.wang.vedio.adapter.index.VipAdapter;
import com.wang.vedio.base.BaseActivity;
import com.wang.vedio.net.SharedHelper;
import com.wang.vedio.net.entity.BaseBean;
import com.wang.vedio.net.entity.VipBean;
import com.wang.vedio.net.entity.VipResult;
import com.wang.vedio.net.entity.XiaDanBean;
import com.wang.vedio.net.rxjava.HttpMethods;
import com.wang.vedio.net.subscribers.ProgressSubscriber;
import com.wang.vedio.net.subscribers.SubscriberOnNextListener;
import com.wang.vedio.utils.FileUtils;
import com.wang.vedio.utils.fileutils.OkManager;
import com.wang.vedio.utils.statusbar.StatusBarUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class VipActivity extends BaseActivity {

    @BindView(R.id.backImg)
    ImageView backImg;
    @BindView(R.id.btTv)
    TextView btTv;

    @BindView(R.id.headPic)
    ImageView headPic;
    @BindView(R.id.person_username)
    TextView person_username;
    @BindView(R.id.img1)
    ImageView img1;
    @BindView(R.id.vipTv)
    TextView vipTv;


    @BindView(R.id.vipztLinear)
    View vipztLinear;
    @BindView(R.id.kefuLinear)
    View kefuLinear;

    @BindView(R.id.rec_main)
    RecyclerView rec_main;

    @BindView(R.id.ljktBtn)
    TextView ljktBtn;
    @BindView(R.id.titleLinear)
    View titleLinear;


    @BindView(R.id.wxxzLinear)
    View wxxzLinear;
    @BindView(R.id.wxxzImg)
    ImageView wxxzImg;

    @BindView(R.id.zfbxzLinear)
    View zfbxzLinear;
    @BindView(R.id.zfbxzImg)
    ImageView zfbxzImg;

    @BindView(R.id.yhkxzLinear)
    View yhkxzLinear;
    @BindView(R.id.yhkxzImg)
    ImageView yhkxzImg;

    @BindView(R.id.bgImg)
    ImageView bgImg;




    private TextView[] btnArgs = new TextView[7];
    private TextView[] vedioArgs = new TextView[7];

    @Override
    protected int getLayoutId() {
        return R.layout.gyss_vip_layout;
    }

    private int type;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        StatusBarUtil.setStatusBar(this, true, R.color.transparent, false, false);
        init();
        titleLinear.setPadding(0, com.wang.vedio.view.StatusBarUtil.getStatusBarHeight(mContext), 0, 0);
    }

    private List<VipBean> yqList = new ArrayList<>();
    private VipAdapter mAdapter;
    private int selectPosition = -1;
    private VipBean selectVip;

    private void init() {
        yqList.clear();
        ((SimpleItemAnimator) rec_main.getItemAnimator()).setSupportsChangeAnimations(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        rec_main.setLayoutManager(linearLayoutManager);
        mAdapter = new VipAdapter(R.layout.item_vip_list, yqList);
        rec_main.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                selectPosition = position;
                selectVip = yqList.get(position);
                mAdapter.setSelectPosition(selectPosition);
            }
        });
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    private void getData() {
        SubscriberOnNextListener<BaseBean<VipResult>> onNextListener = baseBean -> {

            person_username.setText(baseBean.getData().getNcName());

            Glide.with(headPic)
                    .load(HttpMethods.BASE_URL + baseBean.getData().getHeadPic())
                    .apply(RequestOptions.bitmapTransform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(90))))
                    .into(headPic);

            String fmImg = baseBean.getData().getBgImage();

            RequestOptions options = new RequestOptions()
                    .placeholder(-1)//图片加载出来前，显示的图片
                    .fallback(-1) //url为空的时候,显示的图片
                    .error(-1);//图片加载失败后，显示的图片
            Glide.with(mContext).load(HttpMethods.BASE_URL+fmImg).apply(options).into(bgImg);

            vipTv.setText(baseBean.getData().getVipTiShi());
            if ("VIP会员".equals(baseBean.getData().getVipTiShi())) {
                vipztLinear.setBackgroundResource(R.drawable.btn_orange_shape);
            } else {
                vipztLinear.setBackgroundResource(R.drawable.btn_gray_10_shape);
            }
            yqList.clear();
            yqList.addAll(baseBean.getData().getVipList());
            mAdapter.notifyDataSetChanged();
        };
        Map<String, Object> params = new HashMap<>();
        params.put("memberId", SharedHelper.readId(mContext));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().getVipList(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    private void buyVip() {
        SubscriberOnNextListener<BaseBean<XiaDanBean>> onNextListener = baseBean -> {
            RxToast.normal(baseBean.getMessage());
            initPayDialog(baseBean.getData().getPayMoney(), baseBean.getData().getEwmPath(), baseBean.getData().getCardName(),baseBean.getData().getCardNo(),baseBean.getData().getSsyhInfo());
        };
        Map<String, Object> params = new HashMap<>();
        params.put("id", selectVip.getId());
        params.put("memberId", SharedHelper.readId(mContext));
        params.put("adCode",payType);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().createOrderForm(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    private void initPayDialog(String payMoney, String ewmPath,String cardName,String cardNo,String ssyhInfo) {
        PayDialog payDialog = new PayDialog(mContext);
        View zfbwxLinear = payDialog.findViewById(R.id.zfbwxLinear);
        View yhkLinear = payDialog.findViewById(R.id.yhkLinear);
        if(!"银行卡".equals(payType)){
            zfbwxLinear.setVisibility(View.VISIBLE);
            yhkLinear.setVisibility(View.GONE);
            TextView labelTv = payDialog.findViewById(R.id.labelTv);
            TextView zfxxTv = payDialog.findViewById(R.id.zfxxTv);
            ImageView ewmImage = payDialog.findViewById(R.id.ewmImage);
            TextView fzewmTv = payDialog.findViewById(R.id.fzewmTv);
            labelTv.setText("请使用"+payType+"扫码支付");
            zfxxTv.setText("支付"+payMoney+"元");
            Glide.with(ewmImage)
                    .load(HttpMethods.BASE_URL + ewmPath)
                    .apply(RequestOptions.bitmapTransform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(10))))
                    .into(ewmImage);

            fzewmTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //保存支付宝
                    downFile(HttpMethods.BASE_URL + ewmPath, "ewmzf.jpg");
                }
            });
        }else{
            zfbwxLinear.setVisibility(View.GONE);
            yhkLinear.setVisibility(View.VISIBLE);
            TextView yhkzfxxTv = payDialog.findViewById(R.id.yhkzfxxTv);
            TextView yhkName = payDialog.findViewById(R.id.yhkName);
            TextView yhkNameFz = payDialog.findViewById(R.id.yhkNameFz);
            TextView yhkNo = payDialog.findViewById(R.id.yhkNo);
            TextView yhkNoFz = payDialog.findViewById(R.id.yhkNoFz);
            TextView ssyhName = payDialog.findViewById(R.id.ssyhName);
            TextView ssyhNameFz = payDialog.findViewById(R.id.ssyhNameFz);

            yhkzfxxTv.setText("支付："+payMoney+"元");

            yhkName.setText("账户名称："+cardName);
            yhkNo.setText("收款账号："+cardNo);
            ssyhName.setText("收款银行："+ssyhInfo);

            yhkNameFz.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    cm.setText(cardName);
                    RxToast.normal("复制成功！");
                }
            });
            yhkNoFz.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    cm.setText(cardNo);
                    RxToast.normal("复制成功！");
                }
            });
            ssyhNameFz.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    cm.setText(ssyhInfo);
                    RxToast.normal("复制成功！");
                }
            });
        }
        payDialog.show();
    }

    private void downFile(String downUrl, String fileName) {
        File pFile = new File(FileUtils.getRootFile(), fileName);
        if (pFile.exists()) {
            pFile.delete();
        }
        initDownDialog();
        OkManager.getInstance().downLoadFile(downUrl, fileName, new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                downDialog.dismiss();
                if (msg.what == 100) {
                    RxToast.normal("保存成功，赶紧去支付！");
                    //发送广播通知系统图库刷新数据
                    Uri uri = Uri.fromFile(pFile);
                    mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                } else if (msg.what == -1) {
                    RxToast.normal("保存失败！");
                    pFile.delete();
                }
                super.handleMessage(msg);
            }
        });
    }

    private RxDialogDownload downDialog;

    private void initDownDialog() {
        downDialog = new RxDialogDownload(this);
        downDialog.setCanceledOnTouchOutside(false);
        downDialog.getTextView().setText("下载中...");
        downDialog.show();
    }

    private String payType = "微信"; //支付宝；微信；银行卡；
    @OnClick({R.id.ljktBtn, R.id.kefuLinear, R.id.backImg,R.id.yhkxzLinear,R.id.wxxzLinear,R.id.zfbxzLinear})
    public void onClick(View v) {
        if (v.getId() == R.id.ljktBtn) {
            if (selectVip == null) {
                RxToast.normal("请选择充值VIP");
                return;
            }
            buyVip();
        } else if (v.getId() == R.id.backImg) {
            finish();
        } else if(v.getId() == R.id.wxxzLinear){
            payType = "微信";
            wxxzImg.setImageResource(R.mipmap.ic_danxuan_select);
            zfbxzImg.setImageResource(R.mipmap.ic_danxuan_unselect);
            yhkxzImg.setImageResource(R.mipmap.ic_danxuan_unselect);
        } else if(v.getId() == R.id.zfbxzLinear){
            payType = "支付宝";
            wxxzImg.setImageResource(R.mipmap.ic_danxuan_unselect);
            zfbxzImg.setImageResource(R.mipmap.ic_danxuan_select);
            yhkxzImg.setImageResource(R.mipmap.ic_danxuan_unselect);
        } else if(v.getId() == R.id.yhkxzLinear){
            payType = "银行卡";
            wxxzImg.setImageResource(R.mipmap.ic_danxuan_unselect);
            zfbxzImg.setImageResource(R.mipmap.ic_danxuan_unselect);
            yhkxzImg.setImageResource(R.mipmap.ic_danxuan_select);
        } else {
            //去客服界面
            RxActivityTool.skipActivity(mContext, KeFuActivity.class);
        }
    }
}
